<?php

namespace polymerize\user\module\user;

use app\common\InstanceTrait;
use app\common\LoginType;
use app\common\SmsType;
use app\model\User as UserModel;
use app\model\UserBehaviorLog;
use support\Cache;
use support\Redis;

class ChangePassword
{
    use InstanceTrait;

    /**
     * 手机验证码修改密码[发送短信验证]
     *
     * @param int    $uid
     * @param string $mobile
     * @param int    $smsCode
     * @param string $password
     * @return array
     */
    public function changePassword(int $uid, string $mobile, int $smsCode, string $password): array
    {
        //判断手机号是否为当前登录用户的手机号
        $where[]    = ['id', '=', $uid];
        $userMobile = UserModel::where($where)->value('mobile');
        if ($mobile != $userMobile) return ['code' => 400, 'msg' => '请输入正确的手机号码'];

        $expireTime = 2;
        $lockKey    = __METHOD__ . $mobile;
        $lock       = Redis::setNx($lockKey, 1);
        Redis::expire($lockKey, $expireTime);
        if (!$lock) return ['code' => 400, 'msg' => MANY_TIMES_REQUEST];
        $smsKey = 'SMS_CODE_' . md5($mobile . SmsType::SMS_CODE_CHANGE_PASSWORD->value);
        if ($smsCode != Cache::get($smsKey)) return ['code' => 400, 'msg' => '短信验证码错误'];
        Cache::delete($smsKey);
        if (Redis::ttl($lockKey) == -1) Redis::expire($lockKey, $expireTime);  //防止死锁

        $param = [
            'uid'         => $uid,
            'type'        => 3,
            'user_status' => 1,
            'status'      => 1,
            'login_type'  => LoginType::LOGIN_TYPE_PHONE->value
        ];
        UserBehaviorLog::log($param);

        //修改密码 md5(md5(12345).id)
        $data = [
            'password' => md5($password . $uid),
            'u_time'   => myDate()
        ];
        UserModel::updateDataCache($where, $data);

        return ['code' => 200, 'msg' => ''];
    }
}
